<template>
  <div style="padding: 5px;">
    <a-spin :spinning="spinning !== 0">
      <!-- 头部插槽 -->
      <component
        ref="header"
        v-if="header.show"
        :is="header.componentFile"
        :stores="stores"
      />

      <!-- 查询区域 -->
      <div class="table-page-search-wrapper" v-if="queryColumns.length > 0">
        <a-form layout="horizontal" @keyup.enter.native="searchQuery">
          <a-row :gutter="8">
            <a-col v-for="(query, index) in queryColumns" :key="query.colCode"
                   :span="query.queryFormatJson.compColSpan || 6"
                   v-if="query.queryIsHidden !== 'Y'">
              <a-form-item :label="$locale(query.queryAlias || query.colName)" :labelCol="typeof query.queryFormatJson.labelColSpan !== 'undefined' ? {span: query.queryFormatJson.labelColSpan} : labelCol" :wrapperCol="typeof query.queryFormatJson.wrapperColSpan !== 'undefined' ? {span: query.queryFormatJson.wrapperColSpan} : wrapperCol">
                <query-field :placeholder="$locale(query.queryFormatJson.placeholder || query.queryAlias || query.colName)" v-model="query.queryDefaultValue" :type="query.showType"
                             :linkageMap="linkageMap"
                             @setLinkageMap="changeQueryField(query, $event)"
                             :showConfig="query.queryFormatJson"
                             :dictOptions="dictOptions" :dictOptionsFlg="dictOptionsFlg"></query-field>
              </a-form-item>
            </a-col>
            <template v-if="toggleSearchStatus">
              <a-col v-for="(query, index) in queryColumns" :key="query.colCode"
                     :span="query.queryFormatJson.compColSpan || 6"
                     v-if="query.queryIsHidden === 'Y'">
                <a-form-item :label="$locale(query.queryAlias || query.colName)" :labelCol="typeof query.queryFormatJson.labelColSpan !== 'undefined' ? {span: query.queryFormatJson.labelColSpan} : labelCol" :wrapperCol="typeof query.queryFormatJson.wrapperColSpan !== 'undefined' ? {span: query.queryFormatJson.wrapperColSpan} : wrapperCol">
                  <query-field :placeholder="$locale(query.queryFormatJson.placeholder || query.queryAlias || query.colName)" v-model="query.queryDefaultValue" :type="query.showType"
                               :linkageMap="linkageMap"
                               @setLinkageMap="changeQueryField(query, $event)"
                               :showConfig="query.queryFormatJson"
                               :dictOptions="dictOptions" :dictOptionsFlg="dictOptionsFlg"></query-field>
                </a-form-item>
              </a-col>
            </template>
            <a-col :span="6">
              <span style="margin-top: 4px;" class="table-page-search-submitButtons">
                <a-button type="primary" @click="searchQuery" icon="search">{{ $t('m.common.button.query') }}</a-button>
                <a-button type="default" @click="searchReset" icon="reload" style="margin-left: 8px">{{ $t('m.common.button.reset') }}</a-button>
                <a @click="handleToggleSearch" style="margin-left: 8px" v-if="needToggleSearchStatus">
                  {{ toggleSearchStatus ? this.$t('m.common.button.fold') : this.$t('m.common.button.expand') }}
                  <ych-icon :type="toggleSearchStatus ? 'up' : 'down'"/>
                </a>
              </span>
            </a-col>
          </a-row>
        </a-form>
      </div>
      <!-- 查询区域-END -->

      <div style="position: relative; top: -20px; float: right; height: 0;">
        <YchTableColSettings
          style="height: 16px; width: 16px;"
          :tableKey="viewCode"
          :initSettingColumns = "originalColumns"
          @customColumnChange="customColumnChange"
        >
        </YchTableColSettings>
      </div>

      <!-- table区域-begin -->
      <div>
        <a-table
          ref="table"
          size="middle"
          bordered
          rowKey="id"
          :columns="columns"
          :dataSource="dataSource"
          :pagination="pagination"
          :rowSelection="rowSelection"
          :scroll="scroll"
          @change="handleTableChange"
          :customRow="clickThenCheck"
        >
          <template slot="serialNum" slot-scope="text,record,index">
            {{pagination?((pagination.current-1) * pagination.pageSize + parseInt(index) + 1):parseInt(index)+1}}
          </template>
          <template slot="image" slot-scope="text, record">
            <ViewImageSlot v-model="text"/>
          </template>

          <template slot="file" slot-scope="text, record">
            <ViewFileSlot v-model="text"/>
          </template>

          <template slot="links" slot-scope="text, record">
            <a :href="text" target="_blank">{{text}}</a>
          </template>

          <template slot="switch" slot-scope="text, record">
            <a-switch :disabled="true" :checked="text === 'true'"/>
          </template>

          <template slot="html" slot-scope="text, record">
            <div v-html="text"></div>
          </template>
        </a-table>
      </div>

      <!-- 尾部插槽 -->
      <component
        ref="footer"
        v-if="footer.show"
        :is="footer.componentFile"
        :stores="stores"
      />
    </a-spin>
  </div>
</template>

<script>

  import { getAction, deleteAction, putAction, postAction, httpAction } from '@/api/manage'
  import QueryField from '../tag/QueryField'
  import { initDictOptionMap } from '@/components/dict/YchDictSelectUtil'
  import ViewImageSlot from '../../redirect/ViewImageSlot'
  import ViewFileSlot from '../../redirect/ViewFileSlot'
  import YchConstant from '@/api/YchConstant'
  import {handleCreateFunc, handleExecFunc} from '@/utils/actions'
  import YchTableColSettings from '@/components/ych/YchTableColSettings'
  import error from "../../../common/exception/404";

  export default {
    name: 'ViewSelectRedirect',
    components: {
      QueryField,
      ViewImageSlot,
      ViewFileSlot,
      YchTableColSettings,
    },
    props: {
      viewCode: String,
      multi: Boolean,
      rows: Array,
      keys: Array,
      fks: {
        type: Array,
        default: () => []
      },
      parameterValue: {
        type: Array,
        default: () => []
      },
      stores: {
        type: Object,
        default: () => {
          return {}
        }
      }
    },
    data() {
      return {
        header: {show: false},
        footer: {show: false},
        queryColumns: [],
        columns: [],
        originalColumns: [],
        dictOptions: {},
        linkageMap: {},
        dictOptionsFlg: 0,
        columnLineNum: {
          title:this.$t('m.common.label.number'),
          dataIndex: '',
          key: 'rowIndex',
          width: 50,
          align: 'center',
          scopedSlots: { customRender: 'serialNum' },
        },
        rowSelection: {
          selectedRowKeys: this.keys,
          selectionRows: this.rows,
          onChange: (selectedRowKeys, selectionRows) => {
            this.rowSelection.selectedRowKeys = selectedRowKeys
            const aa = this.rowSelection.selectionRows.filter(item => selectedRowKeys.indexOf(item.id) !== -1)
            const bb = aa.map(row => row['id'])
            const cc = selectionRows.filter(item => bb.indexOf(item.id) === -1)
            this.rowSelection.selectionRows = [...aa, ...cc]
          },
          type: this.multi ? 'checkbox' : 'radio'
        },
        dataSource: [],
        scroll: {},
        pagination: {
          current: 1,
          pageSize: 10,
          pageSizeOptions: ['10', '20', '50', '100', '200', '500'],
          showTotal: (total, range) => {
            return this.$t('m.common.label.page_total', [range[0], range[1], total])
          },
          showQuickJumper: true,
          showSizeChanger: true,
          total: 0
        },
        sorter:{},
        spinning: 0,
        toggleSearchStatus: false,
        needToggleSearchStatus: false,
        url: {
          getViewModel: YchConstant.PREFIX_EFORM + '/engine/viewEngine/getViewModel',
          queryViewListPage: YchConstant.PREFIX_EFORM + '/engine/viewEngine/queryViewListPage',
          queryViewList: YchConstant.PREFIX_EFORM + '/engine/viewEngine/queryViewList'
        },
        tableShow: {},
        labelCol: {
          span: 8
        },
        wrapperCol: {
          span: 16
        },
      }
    },
    created() {
      this.spinning++
      getAction(this.url.getViewModel, { viewCode: this.viewCode }).then((res) => {
        if (res.success) {
          this.init(res.result)
        } else {
          this.messageUtil.warning(res.message)
        }
      }).finally(() => {
        this.spinning--
      })
    },
    methods: {
      customColumnChange(settingColumns){
        this.columns = settingColumns.filter(item=>item.visible === true)
      },
      init(result) {
        const that = this
        this.tableShow = result.tableShow
        this.$emit("setDialogTitle", result.tableShow.dialogTitle)
        //查询条件
        this.queryColumns = result.queryShow || []

        this.queryColumns.forEach(query => {
          query.queryFormatJson = query.queryFormat ? JSON.parse(query.queryFormat) : {}

          if (query.queryFormatJson.dictOption && query.queryFormatJson.dictOption.dictCode) {
            that.dictOptions[query.queryFormatJson.dictOption.dictCode] = []
          }
        })
        this.needToggleSearchStatus = this.queryColumns.filter(vo => vo.queryIsHidden === 'Y').length > 0

        //行号
        if (result.tableShow.isLineNum === 'Y') {
          this.columns.push(this.columnLineNum)
        }
        // 临时变量，判断有无居左固定列
        let left_flg = false;
        result.tableShow.columnShow.forEach(vo => {
          const column = {
            title: this.$locale(vo.colAlias || vo.colName),
            dataIndex: vo.colCode,
            mergeHeaderName: vo.mergeHeaderName,
          }
          if (vo.alignType) {
            column.align = vo.alignType
          }
          //宽度
          if (vo.colWidth) {
            column.width = vo.colWidth + "px"
          }
          // 固定列
          if(vo.fixed && vo.fixed !== 'none' && result.tableShow.scrollEnable === 'Y'){
            column.fixed = vo.fixed
            if(vo.fixed === 'left'){
              left_flg = true;
            }
          }
          // 超宽自动省略
          if(vo.isEllipsis === 'Y'){
            column.ellipsis = true;
          }
          //是否可排序
          if(vo.isSort === 'Y'){
            column.sorter = true;
          }
          // 数据转换配置
          if (vo.dataConfig) {
            const dataConfig = JSON.parse(vo.dataConfig)
            if (dataConfig.type === 'image') {
              // 转换成图片
              column.scopedSlots = { customRender: 'image' }
            } else if (dataConfig.type === 'file') {
              // 转换成附件
              column.scopedSlots = { customRender: 'file' }
            } else if (dataConfig.type === 'links') {
              // 转换成超链接
              column.scopedSlots = { customRender: 'links' }
            } else if (dataConfig.type === 'switch') {
              // 转换成开关
              column.scopedSlots = { customRender: 'switch' }
            } else if (dataConfig.type === 'html') {
              // 转换成html
              column.scopedSlots = { customRender: 'html' }
            } else if(dataConfig.type === 'ellipsis'){
              // 转换成不换行，兼容历史
              column.customRender = true;
            }
          }
          this.columns.push(column)
        })

        // 行号居左
        if(left_flg){
          this.columnLineNum.fixed = 'left'
        }

        this.initDictConfig()

        //是否分页
        if (result.tableShow.isPage === 'N') {
          this.pagination = false
        } else {
          //初始分页大小
          if (result.tableShow.pageNum && result.tableShow.pageNum > 0) {
            this.pagination.pageSize = result.tableShow.pageNum
          }
        }

        //是否横向滚动
        if (result.tableShow.scrollEnable === 'Y') {
          const scrollWidth = result.tableShow.scrollWidth || 1300
          this.scroll = {
            x: scrollWidth
          }
        } else {
          this.scroll = {}
        }

        // 合并表头
        this.mergeHeader();

        //深拷贝
        let dealColumns = [];
        this.columns.map(item => {
          let newObj = Object.assign({}, item);
          newObj['visible'] = item.visible !== false
          dealColumns.push(newObj);
        });
        //原始列信息
        this.originalColumns = dealColumns

        // 插槽
        const customSlot = result.tableShow.customSlot ? JSON.parse(result.tableShow.customSlot) : {}
        if (customSlot.header) {
          this.header.componentFile = (resolve) => ({
            component: import(`@/views/` + customSlot.header + '.vue'),
            error: error,
            delay: 200,
            timeout: 10000
          })
          this.header.show = true
        }
        if (customSlot.footer) {
          this.footer.componentFile = (resolve) => ({
            component: import(`@/views/` + customSlot.footer + '.vue'),
            error: error,
            delay: 200,
            timeout: 10000
          })
          this.footer.show = true
        }

        //默认查询
        if (result.tableShow.isQuery === 'Y') {
          this.loadData()
        }
      },
      mergeHeader(){
        //合并表头处理
        let mergeHeaderNameMap = new Map
        let columnIndex = 0
        let mergeCount = 0
        this.columns.forEach(item => {
            if (item.mergeHeaderName) {
              if (!mergeHeaderNameMap.has(item.mergeHeaderName)) {
                let mergeObj = {
                  index: columnIndex + mergeCount,
                  title: this.$locale(item.mergeHeaderName),
                  children: []
                }
                mergeObj.children.push(item)
                mergeHeaderNameMap.set(item.mergeHeaderName, mergeObj)
                mergeCount++
              } else {
                mergeHeaderNameMap.get(item.mergeHeaderName).children.push(item)
              }
            }
            columnIndex++
          }
        )
        if (mergeHeaderNameMap.size > 0) {
          let newColumns = this.columns
          mergeHeaderNameMap.forEach(item => {
            newColumns.splice(item.index, 0, item)
          })
          this.columns = newColumns.filter(item => !(item.mergeHeaderName && item.mergeHeaderName.length > 0))
        }
      },
      loadData(arg) {
        let url
        if (this.pagination) {
          //加载数据 若传入参数1则加载第一页的内容
          if (arg === 1) {
            this.pagination.current = 1
          }
          url = this.url.queryViewListPage + '?viewCode=' + this.viewCode + '&pageNo=' + this.pagination.current + '&pageSize=' + this.pagination.pageSize
        } else {
          url = this.url.queryViewList + '?viewCode=' + this.viewCode
        }
        //排序字段
        if(this.sorter && this.sorter.field){
          url +="&sorterField="+this.sorter.field
        }
        //升序or降序
        if(this.sorter && this.sorter.order){
          let order = this.sorter.order.substr(0,this.sorter.order.indexOf("end"))
          url +="&sorterOrder="+order
        }

        this.spinning++
        const queryValue = []
        this.queryColumns.forEach(query => {
          //时间范围查询
          if (query.queryDefaultValue && query.queryDefaultValue.startsWith('[') && query.queryDefaultValue.endsWith(']')) {
            const queryDefaultValueJson = JSON.parse(query.queryDefaultValue)
            if (queryDefaultValueJson.length === 2) {
              const item_start = {
                colCode: query.colCode,
                queryValue: queryDefaultValueJson[0]
              }
              const item_end = {
                colCode: query.colCode + '-end',
                queryValue: queryDefaultValueJson[1]
              }
              queryValue.push(item_start)
              queryValue.push(item_end)
            }
          } else if (query.queryDefaultValue) {
            const item = {
              colCode: query.colCode,
              queryValue: query.queryDefaultValue
            }
            queryValue.push(item)
          }
        })
        //加载前事件
        if (this.tableShow.beforeScript) {
          const _that = this
          const func = handleCreateFunc(this.tableShow.beforeScript, this)
          const func_result = handleExecFunc(func, {url, arg, queryValue}, function(){
            _that.loadDataCallback(url, queryValue, arg);
          })
          if(!func_result) return;
        }
        this.loadDataCallback(url, queryValue, arg);
      },
      loadDataCallback(url, queryValue, arg){
        postAction(url, {
          fks: this.fks,
          queryValue: queryValue,
          parameterValue: this.parameterValue
        }).then((res) => {
          if (res.success) {
            if (this.pagination) {
              this.dataSource = res.result.records
              this.pagination.total = res.result.total
            } else {
              this.dataSource = res.result
            }

            //加载后事件
            if (this.tableShow.afterScript) {
              const func = handleCreateFunc(this.tableShow.afterScript, this)
              handleExecFunc(func, {arg, queryValue, res})
            }
          } else {
            this.messageUtil.warning(res.message)
          }
        }).finally(() => {
          this.spinning--
        })
      },
      //查询
      searchQuery() {
        this.loadData(1)
      },
      //重置
      searchReset() {
        this.queryColumns.forEach(vo => vo.queryDefaultValue = undefined)
        this.linkageMap = {}
        this.loadData(1)
      },
      //展开
      handleToggleSearch() {
        this.toggleSearchStatus = !this.toggleSearchStatus
      },
      //分页、排序、筛选变化时触发
      handleTableChange(pagination, filters, sorter) {
        this.pagination = this.pagination ? pagination : false
        this.sorter = sorter
        this.loadData()
      },
      initDictConfig() {
        let dictCodes = Object.keys(this.dictOptions).join(',')
        if (dictCodes && dictCodes.length > 0) {
          initDictOptionMap(dictCodes).then((res) => {
            if (res.success) {
              Object.keys(this.dictOptions).forEach(key => {
                this.$set(this.dictOptions, key, res.result[key])
              })
              //触发查询框重新加载
              this.dictOptionsFlg = this.dictOptionsFlg + 1
            }
          })
        }
      },
      changeQueryField(query, value) {
        if (query.showType && query.colCode) {
          this.linkageMap = {...this.linkageMap}
          this.linkageMap[query.colCode] = value;
        }
      },
      clickThenCheck(record) {
        const that = this
        return {
          on: {
            click: () => {
              if (that.multi) {
                const keys = that.rowSelection.selectedRowKeys.filter(vo => vo !== record.id)
                if (keys.length < that.rowSelection.selectedRowKeys.length) {
                  const rows = that.rowSelection.selectionRows.filter(vo => vo.id !== record.id)
                  that.rowSelection.selectedRowKeys = keys
                  that.rowSelection.selectionRows = rows
                } else {
                  that.rowSelection.selectedRowKeys.push(record.id)
                  that.rowSelection.selectionRows.push(record)
                }
              } else {
                that.rowSelection.selectedRowKeys = [record.id]
                that.rowSelection.selectionRows = [record]
                that.$emit('selected')
              }
            }
          }
        }
      }
    }
  }
</script>
<style lang="less" scoped>
/deep/ .ant-table-thead {
  tr {
    th[colspan="1"] {
      text-align: center;
    }
  }
}
</style>
